//
//  AppOpenAdManager.swift
//  Your Lover AI
//
//  Created by 阿忠 on 2024/7/26.
//

import Foundation
import GoogleMobileAds
import FirebaseRemoteConfigInternal
import SwiftyJSON

protocol AppOpenAdManagerDelegate: AnyObject {
  /// Method to be invoked when an app open ad life cycle is complete (i.e. dismissed or fails to
  /// show).
  func appOpenAdManagerAdDidComplete(_ appOpenAdManager: AppOpenAdManager)
}

class AppOpenAdManager: NSObject {
  /// Ad references in the app open beta will time out after four hours,
  /// but this time limit may change in future beta versions. For details, see:
  /// https://support.google.com/admob/answer/9341964?hl=en
  let timeoutInterval: TimeInterval = 4 * 3_600
  /// The app open ad.
  var appOpenAd: GADAppOpenAd?
  /// Maintains a reference to the delegate.
  weak var appOpenAdManagerDelegate: AppOpenAdManagerDelegate?
  /// Keeps track of if an app open ad is loading.
  var isLoadingAd = false
  /// Keeps track of if an app open ad is showing.
  var isShowingAd = false
  /// Keeps track of the time when an app open ad was loaded to discard expired ad.
  var loadTime: Date?
    
    var remoteConfig: RemoteConfig!
    
    let loadingPhraseConfigKey = "adData"
    
    //全局的广告ID
    var withAdUnitID = "ca-app-pub-3940256099942544/5575463023"
    //广告请求次数
    var adUnitInt = 0

  static let shared = AppOpenAdManager()
    

  private func wasLoadTimeLessThanNHoursAgo(timeoutInterval: TimeInterval) -> Bool {
    // Check if ad was loaded more than n hours ago.
    if let loadTime = loadTime {
      return Date().timeIntervalSince(loadTime) < timeoutInterval
    }
    return false
  }

  private func isAdAvailable() -> Bool {
    // Check if ad exists and can be shown.
    return appOpenAd != nil && wasLoadTimeLessThanNHoursAgo(timeoutInterval: timeoutInterval)
  }

  private func appOpenAdManagerAdDidComplete() {
      //应用打开广告被认为是完成时，它解散或未能显示;
      //如果委托不为nil，调用委托的appopenadmanageraddcomplete方法。
    appOpenAdManagerDelegate?.appOpenAdManagerAdDidComplete(self)
  }

  func loadAd() async {
    // Do not load ad if there is an unused ad or one is already loading.
    if isLoadingAd || isAdAvailable() {
      return
    }
    isLoadingAd = true

    print("Start loading app open ad.")

    do {
        
        //测试
        remoteConfig = RemoteConfig.remoteConfig()
        let str = remoteConfig[loadingPhraseConfigKey].stringValue
//        print(str)
        // 将字符串转换为Data
        if let jsonData = str!.data(using: .utf8) {
            // 尝试解析JSON数据
            do {
                  // 解析JSON数据到字典
                  if let jsonDict = try JSONSerialization.jsonObject(with: jsonData, options: []) as? [String: Any] {
                      let json = JSON.init(jsonDict)
                      let adData = json["adData"]
                      //循环 看有没有开屏广告
                      var i = 0
                      for i in 0..<adData.count {
                          let placement = adData[i]["placement"].stringValue
                          if placement == "open_active_op" {//有开屏广告
                              print("有开屏广告")
                              let withAdUnitID = json["adData"][i]["data"][0]["adId"].stringValue
                              self.withAdUnitID = withAdUnitID
        //                      print(withAdUnitID)
        //                      print("-------------------获取成功了--------------")
                              appOpenAd = try await GADAppOpenAd.load(
                                withAdUnitID: self.withAdUnitID, request: GADRequest())
                              appOpenAd?.fullScreenContentDelegate = self
                              loadTime = Date()
                              
                              let adUnitint = json["rules"]["platforms"][0]["request"].intValue
        //                      print(adUnitint)
                              if self.adUnitInt > adUnitint{
                                  return
                              }else{
                                  self.adUnitInt += 1
                              }
                          }
                      }
                      
                     
                      
                  }
              } catch {
                  print("解析错误: \(error.localizedDescription)")
              }
        }

        
      
    } catch {
      appOpenAd = nil
      loadTime = nil
      print("App open ad failed to load with error: \(error.localizedDescription)")
    }
    isLoadingAd = false
  }

  func showAdIfAvailable() {
    // 如果应用打开广告已经显示，不要再显示广告。
    if isShowingAd {
      print("App open ad is already showing.")
      return
    }
      //如果应用程序的open广告还不可用，但它应该显示，
      //调用appopenadmanageraddcomplete方法并加载一个新广告。
    if !isAdAvailable() {
      print("App open ad is not ready yet.")
      appOpenAdManagerAdDidComplete()
//      if GoogleMobileAdsConsentManager.shared.canRequestAds {
        Task {
          await loadAd()
        }
//      }
      return
    }
    if let ad = appOpenAd {
      print("App open ad will be displayed.")
      isShowingAd = true
      ad.present(fromRootViewController: nil)
    }
  }
}

extension AppOpenAdManager: GADFullScreenContentDelegate {
  func adWillPresentFullScreenContent(_ ad: GADFullScreenPresentingAd) {
    print("App open ad is will be presented.")
  }

  func adDidDismissFullScreenContent(_ ad: GADFullScreenPresentingAd) {
//      NotificationCenter.default.post(name: Notification.Name("openAd"), object: nil, userInfo: ["key": "value"])
    appOpenAd = nil
    isShowingAd = false
    print("广告完整打开.")
    appOpenAdManagerAdDidComplete()
    Task {
      await loadAd()
    }
  }

  func ad(
    _ ad: GADFullScreenPresentingAd,
    didFailToPresentFullScreenContentWithError error: Error
  ) {
    appOpenAd = nil
    isShowingAd = false
    print("广告报错: \(error.localizedDescription)")
    appOpenAdManagerAdDidComplete()
    Task {
      await loadAd()
    }
  }
}
